/**
 * 后退按钮 指令控制
 */
define(['angular'], function (angular) {
    "use strict";

    var directive = function ($ionicPlatform,$ionicHistory, $state) {
        return {
            restrict: "E",
            replace:true,
            template: '<button class="button back-button buttons button-icon icon ion-ios7-arrow-back header-item btnBack" ng-click="onBackKeyDown()"></button>',
            link: function(scope) {
                if(!scope.onBackKeyDown){
                    scope.onBackKeyDown = function(){
                        if($ionicHistory.backView() == null && $ionicHistory.currentView().stateName != "tab.index") {
                            $state.go("tab.index");
                        }
                        if($ionicHistory.backView() && $ionicHistory.backView().stateId == $ionicHistory.currentView().stateId) {
                            var i=-1;
                            while($ionicHistory.backView().stateId == $ionicHistory.currentView().stateId) {
                                i--;
                                $ionicHistory.goBack(i);
                            }
                        } else {
                            $ionicHistory.goBack();
                        }
                    }
                }
                if(ionic.Platform.isAndroid()){
                    $ionicPlatform.registerBackButtonAction(function (e) {
                        scope.onBackKeyDown();
                        e.preventDefault();
                        return false;
                    }, 101);
                }
            }
        }
    };

    directive.$inject = ['$ionicPlatform','$ionicHistory', '$state'];
    return directive;
});